<?php

namespace app\modules\admin\services;

use app\common\services\BaseService;
use app\components\pagination\Pagination;
use app\config\Constants;
use app\models\User;

class UserService extends BaseService{

    /**
     * 搜索
     * @param $username
     * @param $mobile
     * @param $type
     * @param $status
     * @param $page
     * @param $pagesize
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function search($username,$mobile,$type,$status,&$page,$pagesize){
        $query = User::find()->asArray(true)
            ->orderBy(['user_id'=>SORT_DESC]);

        if(!empty($username)){
            $query->andWhere(['like','username',$username]);
        }
        if(!empty($mobile)){
            $query->andWhere(['like','mobile',$mobile]);
        }
        if(!empty($type)){
            if($type == Constants::TYPE_STORE){
                $ids = InfoService::getStoreIds();
            }else{
                $ids = InfoService::getUserIds();
            }
            $query->andWhere(['in','user_id',$ids]);
        }
        if(!empty($status)){
            $query->andWhere(['status'=>$status]);
        }

        $page = new Pagination(['totalCount' => $query->count(), 'pageSize' => $pagesize]);
        $query->offset($page->getOffset());
        $query->limit($page->getLimit());

        $data = $query->all();

        foreach($data as $k=>$v){
            $data[$k]['info'] = InfoService::getInfoById($v['user_id']);
        }
        return $data;
    }

    /**
     * 更新状态
     * @param $id
     * @param $status
     * @return bool|void
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function updateStatusById($id, $status)
    {
        $model = User::findOne($id);
        if(!$model){
            return;
        }
        $model->setAttribute("status",$status);
        return $model->update() !== false;
    }
}